//
//  SessionMessageCell.m
//  AirMessage
//
//  Created by 陈区 on 13-2-5.
//  Copyright (c) 2013年 陈区. All rights reserved.
//

#import "SessionMessageCell.h"
#import "SEGSessionMessageUserDetailViewController.h"

@interface BgImageView ()

@property (nonatomic, copy) NSString *userID;

@end

@implementation BgImageView

@synthesize parentCell;

- (BOOL)canBecomeFirstResponder
{
    return YES;
}
@end

#pragma mark - 实现

@implementation SessionMessageCell

@synthesize cellDelegate;
@synthesize bubbleImageView;
@synthesize lbMsgBody;
@synthesize btnHeadImage;
@synthesize showImage;
@synthesize index;
@synthesize headerView;
@synthesize contentViewCell;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString*)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

#pragma mark -
#pragma mark 我发的消息

//我发的信息
- (void)initWithSessionMessageForMe:(MessageModel*)sessionMessage
{
    
    UIView* tmpView = nil;
    if ([cellDelegate respondsToSelector:@selector(sessionMessageCell:viewForHeaderInCell:)] && index) {
        tmpView = [cellDelegate sessionMessageCell:self viewForHeaderInCell:index];
    }
    if (tmpView) {
        self.headerView = tmpView;
        headerView.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:headerView];
    }
    else {
        self.headerView = nil;
    }
    
    //单元格内容视图
    contentViewCell = [[UIView alloc] initWithFrame:CGRectZero];
    contentViewCell.backgroundColor = [UIColor clearColor];
    contentViewCell.userInteractionEnabled = YES;
    [self.contentView addSubview:contentViewCell];
    
    //创建可拉升的泡泡
    UIImage* bubble = [UIImage imageWithContentsOfFile:SEGPicName(@"message_bg_g")];
    
    self.bubbleImageView = [[BgImageView alloc] initWithImage:
                             [bubble stretchableImageWithLeftCapWidth:IM_RIGHT_BUBBLE_IMAGE_LEFT_CAP_WIDTH - 20
                                                         topCapHeight:IM_RIGHT_BUBBLE_IMAGE_TOP_CAP_HEIGHT]];
    self.bubbleImageView.parentCell = self;
    
    float cellHeight = 0.0f;
    
    //contenttype 1：文本   2图片 5：借条    else：默认文本
    if ([sessionMessage.contenttype isEqualToString:@"1"]) { // 文本
        self.userInteractionEnabled = YES;
        bubbleImageView.userInteractionEnabled = YES;
        //设置文字标签和气泡
        [self setUpTextBubbleWithMessage:sessionMessage.message isLeft:NO];
    }
    //    else if ([sessionMessage.contenttype isEqualToString:@"5"]) { // 借条
    //        [self setUpLoanWithIsLeft:NO];
    //    }

    [contentViewCell addSubview:self.bubbleImageView];
    
    //头像
    self.btnHeadImage = [[UIImageView alloc] init];
    self.btnHeadImage.frame = CGRectMake(bubbleImageView.frame.origin.x + bubbleImageView.frame.size.width + IM_HEADER_IMAGE_BUBBLE_CAP_WIDTH, bubbleImageView.frame.origin.y, IM_HEADER_IMAGE_WIDTH_HEIGHT, IM_HEADER_IMAGE_WIDTH_HEIGHT);
//    self.btnHeadImage.layer.cornerRadius = 5.f;
    self.btnHeadImage.layer.borderColor = [UIColor whiteColor].CGColor;
//    self.btnHeadImage.layer.masksToBounds = YES;
    [self.btnHeadImage seg_configWithRadius:5];
    SEGProfileModel *sysAccount = [SEGProfileManager sharedManager].profile;
    [self.btnHeadImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kClientImageRootURL,sysAccount.ico]] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"headimg82")] options:SDWebImageLowPriority];
    [contentViewCell addSubview:self.btnHeadImage];
    [self addHeadImageTap];
    
    cellHeight = self.bubbleImageView.frame.size.height + IM_CELL_TOP_CAP_HEIGHT * 2;
    
    //上下各留10xp
    float headerHeight = (headerView != nil ? headerView.frame.size.height : 0);
    contentViewCell.frame = CGRectMake(0, headerHeight, [UIScreen mainScreen].bounds.size.width, cellHeight);
    //    contentViewCell.backgroundColor=[UIColor yellowColor];
    self.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, headerHeight + cellHeight);
}

//#pragma mark 借条详情点击
//
//- (void)tapAction:(UITapGestureRecognizer*)tap
//{
//    [cellDelegate loanClicked:@"goodsId"];
//}

#pragma mark -
#pragma mark 好友发的消息

//好友发的消息
- (void)initWithSessionMessageForAnother:(MessageModel*)sessionMessage
{
    
    UIView* tmpView = nil;
    if ([cellDelegate respondsToSelector:@selector(sessionMessageCell:viewForHeaderInCell:)] && index) {
        tmpView = [cellDelegate sessionMessageCell:self viewForHeaderInCell:index];
    }
    if (tmpView) {
        self.headerView = tmpView;
        [self.contentView addSubview:headerView];
    }
    else {
        self.headerView = nil;
    }
    
    //单元格内容视图
    contentViewCell = [[UIView alloc] initWithFrame:CGRectZero];
    contentViewCell.backgroundColor = [UIColor clearColor];
    contentViewCell.userInteractionEnabled = YES;
    [self.contentView addSubview:contentViewCell];
    
    float cellHeight = 0.0f;
    //创建可拉升的泡泡
    UIImage* bubble = [UIImage imageWithContentsOfFile:SEGPicName(@"message_bg_w")];
    
    self.bubbleImageView = [[BgImageView alloc] initWithImage:
                             [bubble stretchableImageWithLeftCapWidth:IM_LEFT_BUBBLE_IMAGE_LEFT_CAP_WIDTH
                                                         topCapHeight:IM_LEFT_BUBBLE_IMAGE_TOP_CAP_HEIGHT]];
    self.bubbleImageView.parentCell = self;
    
    //contenttype 1：文本   2图片 5：借条    else：默认文本
    if ([sessionMessage.contenttype isEqualToString:@"1"]) {
        //设置文字标签和气泡
        [self setUpTextBubbleWithMessage:sessionMessage.message isLeft:YES];
    }
    //    else if ([sessionMessage.contenttype isEqualToString:@"5"]) { //借条
    //        [self setUpLoanWithIsLeft:YES];
    //    }

    [contentViewCell addSubview:self.bubbleImageView];
    
    //用户头像
    self.btnHeadImage = [[UIImageView alloc] init];
    self.btnHeadImage.frame = CGRectMake(IM_HEADER_IMAGE_LEFT_CAP_WIDTH, bubbleImageView.frame.origin.y, IM_HEADER_IMAGE_WIDTH_HEIGHT, IM_HEADER_IMAGE_WIDTH_HEIGHT);
    [self.btnHeadImage seg_configWithRadius:5];
//    self.btnHeadImage.layer.cornerRadius = 5.f;
//    self.btnHeadImage.layer.masksToBounds = YES;
    [contentViewCell addSubview:self.btnHeadImage];
    [self addHeadImageTap];
    
    [self.btnHeadImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kClientImageRootURL, sessionMessage.usericon]]
                      placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"headimg82")]
                               options:SDWebImageLowPriority];
    
    cellHeight = self.bubbleImageView.frame.size.height + IM_CELL_TOP_CAP_HEIGHT * 2;
    
    //上下各留10xp
    float headerHeight = (headerView != nil ? headerView.frame.size.height : 0);
    contentViewCell.frame = CGRectMake(0, headerHeight, [UIScreen mainScreen].bounds.size.width, cellHeight);
    
    self.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, cellHeight + headerHeight);
}

- (void)addHeadImageTap {
    self.btnHeadImage.userInteractionEnabled = YES;
    [self.btnHeadImage addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        SEGSessionMessageUserDetailViewController *detailCtl = [[SEGSessionMessageUserDetailViewController alloc] init];
        detailCtl.hidesBottomBarWhenPushed = YES;
        detailCtl.userID = ValueToString(self.messageModel.sendUserId);
        [self.viewController.navigationController pushViewController:detailCtl animated:YES];
    }]];
}

- (void)reloadMessage:(MessageModel*)aMessage
{
    self.messageModel = aMessage;
    
    //清空子view
    NSArray* subViews = [self.contentView subviews];
    for (UIView* vi in subViews) {
        [vi removeFromSuperview];
    }
    
    switch ([self.messageModel.sendUserType intValue]) {
        case kMessageSenderTypeMe: {
            [self initWithSessionMessageForMe:self.messageModel];
            break;
        }
        case kMessageSenderTypeAnother: {
            [self initWithSessionMessageForAnother:self.messageModel];
            break;
        }
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    self.btnHeadImage = nil;
    self.bubbleImageView = nil;
    self.lbMsgBody = nil;
    self.showImage = nil;
    self.index = nil;
    self.headerView = nil;
    self.contentViewCell = nil;
}
#pragma mark - setUpViews
//设置文字气泡格式和大小
- (void)setUpTextBubbleWithMessage:(NSString*)message isLeft:(BOOL)isLeft
{
    self.lbMsgBody = [SEGLabel new];
    self.lbMsgBody.userInteractionEnabled = YES;
    self.lbMsgBody.lineBreakMode = NSLineBreakByWordWrapping;
    self.lbMsgBody.font = [UIFont systemFontOfSize:15];
    self.lbMsgBody.backgroundColor = [UIColor clearColor];
    self.lbMsgBody.numberOfLines = 0;
    self.lbMsgBody.text = message;
    [self.bubbleImageView addSubview:self.lbMsgBody];

    if (isLeft) { //左边 别人发送的消息
        self.lbMsgBody.textColor = kColor_1;
    }
    else { //右边 自己发送的消息
        self.lbMsgBody.textColor = kColor_W;
    }
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:message];
    text.yy_font = kFont_15;
    text.yy_color = self.lbMsgBody.textColor;
    [text yy_setTextHighlightRange:NSMakeRange(0, message.length) color:self.lbMsgBody.textColor backgroundColor:kColor_bg userInfo:nil tapAction:nil longPressAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = self.lbMsgBody.text;
        [SEGAlertView showTmepMessageWithMessage:@"复制成功"];
    }];
    self.lbMsgBody.attributedText = text;
    
    CGFloat textWidth = IM_CELL_MAX_WIDTH - 24; //文字左右各距10 箭头占4
    CGSize size = [message boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:15] } context:nil].size;
    size.width += 24; //文字左右各距10 箭头占4
    size.height += 20;
    
    //判断气泡的宽度有没有超出最大单元格宽度
    float bubbleWidth = size.width > IM_CELL_MAX_WIDTH ? IM_CELL_MAX_WIDTH : size.width;
    if (size.height > IM_CELL_MIN_HEIGHT) { //多行直接为最大值
        bubbleWidth = IM_CELL_MAX_WIDTH;
    }
    //判断气泡的最小值不能小于规定的最小值
    bubbleWidth = bubbleWidth < IM_CELL_MIN_WIDTH ? IM_CELL_MIN_WIDTH : bubbleWidth;
    //判断气泡的最小高度，不能小于规定的最小值
    float bubbleHeight = size.height < IM_CELL_MIN_HEIGHT ? IM_CELL_MIN_HEIGHT : size.height;
    
    if (isLeft) { //左边 别人发送的消息
        self.bubbleImageView.frame = CGRectMake(IM_HEADER_IMAGE_LEFT_CAP_WIDTH + IM_HEADER_IMAGE_WIDTH_HEIGHT + IM_HEADER_IMAGE_BUBBLE_CAP_WIDTH, IM_CELL_TOP_CAP_HEIGHT, bubbleWidth, bubbleHeight);
        self.lbMsgBody.frame = CGRectMake(14, 0, bubbleWidth - 24, bubbleHeight);
    }
    else { //右边 自己发送的消息
        self.bubbleImageView.frame = CGRectMake(
                                                [UIScreen mainScreen].bounds.size.width - IM_HEADER_IMAGE_WIDTH_HEIGHT - IM_HEADER_IMAGE_BUBBLE_CAP_WIDTH - IM_HEADER_IMAGE_RIGHT_CAP_WIDTH - bubbleWidth,
                                                IM_CELL_TOP_CAP_HEIGHT,
                                                bubbleWidth,
                                                bubbleHeight);
        self.lbMsgBody.frame = CGRectMake(10, 0, bubbleWidth - 24, bubbleHeight);
    }
}
@end
